package Offer.offer2016;

import domain.ListNode;

//�����Ѽ������������й������
public class Test37 {

    public static void main(String[] args) {


    }

    public static ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode p1 = pHead1;
        int length1 = 0;
        while (p1 != null) {
            length1++;
            p1 = p1.next;
        }
        ListNode p2 = pHead2;
        int length2 = 0;
        while (p2 != null) {
            length2++;
            p2 = p2.next;
        }


        int k = length1 - length2;
        ListNode pLong = pHead1;
        ListNode pShort = pHead2;

        if (length1 > length2) {
            k = length1 - length2;
            pLong = pHead2;
            pShort = pHead1;
        }
        for (int i = 0; i < k; i++) {
            pLong = pLong.next;
        }
        while (pLong != null && pShort != null && pLong != pShort) {
            pLong = pLong.next;
            pShort = pShort.next;
        }
        return pLong;
    }
}
